<?php
/**
 * Created by PhpStorm.
 * User: 六花
 * Date: 2019/4/27
 * Time: 17:20
 */

namespace Crontab\Controller;

require_once("/opt/vendor/autoload.php");

use Crontab\Model\GoodsSpecModel;
use Think\Controller;
use think\Log;


class IndexController extends Controller {


    public function index(){
        echo '123';
    }

    public function changeOrder(){
        $condOrder['add_time'] = array('elt',time()-30*60);
        $condOrder['status'] = 11;
        $res = M('order')->where($condOrder)->field('order_id')->select();
        $arr = array();
        if(!$res){
            return;
        }
        foreach ($res as $k => $v){
            array_push($arr, $v['order_id']);
        }
        $cond['order_id'] = array('in',$arr);
        M('order_extm')->startTrans();
        $res_extm = M('order_extm')->where($cond)->delete();
        if($res_extm === false){
            M('order_extm')->rollback();
            return false;
        }
        $res_og = M('order_goods')->where($cond)->select();
        if(!$res_og){
            M('order_extm')->rollback();
            return false;
        }
        foreach ($res_og as $k => $v){
            $res_save = M('goods_spec')->where(array('spec_id'=>$v['spec_id']))->setInc('stock');
            if(!$res_save){
                M('order_extm')->rollback();
                return false;
            }
        }
        $res_goods = M('order_goods')->where($cond)->delete();
        if($res_goods === false){
            M('order_extm')->rollback();
            return false;
        }
        $res_order_select = M('order')->where($cond)->select();
        foreach ($res_order_select as $key => $value){
            if($value['coupon_id']){
                $data_coupon = array(
                    'is_used' => 0,
                    'use_time' => 0,
                );
                $res_coupon = M('member_coupon')->where(array('id'=>$value['coupon_id']))->save($data_coupon);
            }
            if($res_coupon === false){
                M('order_extm')->rollback();
                return false;
            }
        }
        $res_order = M('order')->where($cond)->delete();
        if($res_order === false){
            M('order_extm')->rollback();
            return false;
        }
        M('order_extm')->commit();
        return true;
    }

    public function saveImages(){
        set_time_limit(0);
        ini_set('display_errors','on');
        error_reporting(E_ALL);
        $cond['is_save'] = 0;
        $cond['is_excute'] = 0;
        $res = M('save_images') -> where($cond)->limit(1)->select();
        $array['id'] = array('in',array_column($res,'id'));

        if($res){
            M('save_images') -> where($array)->save(array('is_excute'=>1));
        }

        foreach ($res as $k =>$v){
            //先查是哪个商品
            $res_goods = M('goods')->where(array('goods_id'=>$v['goods_id']))->find();
            if(!$res_goods){
                $send_array[] = array(
                    'Sku' => $res_goods['swift_number'],
                    'Field' => '',
                    'Msg' => '查找商品失败',
                    "Result" => 0
                );
                sync_data(C('ERP_URL'),$send_array);
                continue;
            }
            $path = '';
            if($v['type'] == 1 || $v['type'] == 3){
                $path = $_SERVER['DOCUMENT_ROOT'].'/data/files/store_'.$v['store_id'].'_old/goods_'.$v['goods_id'].'/';
            }else if($v['type'] == 2){
                $path = $_SERVER['DOCUMENT_ROOT'].'/data/files/store_'.$v['store_id'].'_old/goodsspec/';
            }

            try {

                $file_name = downloadImage($v['image_url'],$path,$v['type'],$res_goods);

                if(!$file_name){
                    continue;
                }

                if(!file_exists($path.$file_name)){
                    $send_array[] = array(
                        'Sku' => $res_goods['swift_number'],
                        'Field' => '',
                        'Msg' => '创建图片路径失败',
                        "Result" => 0
                    );
                    sync_data(C('ERP_URL'),$send_array);
                    continue;
                }
            } catch (Exception $e) {
                continue;
            }

            $thumb_path = './../data/files/store_'.$v['store_id'].'_old/goods_'.$v['goods_id'].'/'.$file_name;
            $save_path = './../data/files/store_'.$v['store_id'].'_old/goods_'.$v['goods_id'].'/small_'.$file_name;

            if($v['type'] == 1){
                try {
                    make_thumb($thumb_path,$save_path);
                } catch (Exception $e) {
                    continue;
                }
            }
            $new_path = str_replace('store_2_old','store_2',$path);
            $path_arr = explode('data',$new_path);
//            $path_arr1 = explode('data',$path);
//            $path_arr = explode('data',$path);
            $path_str = 'data'.$path_arr[2];
            $thumb_str = 'data'.$path_arr[2];
//            $path_str1 = 'data'.$path_arr1[2];
//            $thumb_str1 = 'data'.$path_arr1[2];
            $send_data['id'] = $v['id'];
            $send_data['goods_id'] = $v['goods_id'];
            if($v['type'] == 2){
                $send_data['spec_id'] = $v['spec_id'];
            }else{
                $send_data['spec_id'] = 0;
            }
            $send_data['store_id'] = $v['store_id'];
            $send_data['file_name'] = $file_name;
            $send_data['file_path'] = $path_str.$file_name;
            $send_data['thumb_name'] = 'small_'.$file_name;
            $send_data['thumb_path'] = $thumb_str.'small_'.$file_name;
            \Gregwar\Image\Image::open($path.$file_name)
                ->resize(600, 600)
                ->save($new_path.$file_name, 'jpg', 50);
            \Gregwar\Image\Image::open($path.'small_'.$file_name)
                ->resize(600, 600)
                ->save($new_path.'small_'.$file_name, 'jpg', 50);
//            if(!file_exists(BASE_PATH.$send_data['file_path']) || !file_exists(BASE_PATH.$send_data['thumb_path'])){
//                $send_array[] = array(
//                    'Sku' => $res_goods['swift_number'],
//                    'Field' => '',
//                    'Msg' => '创建缩略图失败---'.BASE_PATH.$send_data['file_path'].'---'.BASE_PATH.$send_data['file_path'],
//                    "Result" => 0
//                );
//                sync_data(C('ERP_URL'),$send_array);
//                continue;
//            }

            try {

                $res_sql = save_sql($send_data,$v['type'],$res_goods);
                if(!$res_sql){
                    continue;
                }

                //验证当前商品是否所有图片已下完
                $res_all = M('save_images')->where('(is_excute = 0 or is_save = 0) and goods_id = '.$v['goods_id'])->select();
                if(!$res_all){
                    $send_array[] = array(
                        'Sku' => $res_goods['swift_number'],
                        'Field' => '',
                        'Msg' => '下载成功',
                        "Result" => 1
                    );
                    $res_stock = sync_data(C('ERP_URL'),$send_array);
                    if($res_stock){
                        $res_open = M('goods')->where(array('goods_id'=>$v['goods_id']))->save(array('closed'=>0));
                    }
                    continue;
                }
            } catch (Exception $e) {
                continue;
            }

        }
    }

    public function createAccount(){
        $cond['ecm_order.status'] = array('IN','20,30,40');
        $first_day = strtotime(date('Y-m-1 00:00:00',strtotime('last month')));
        $last_day = strtotime(date('Y-m-d 23:59:59',strtotime(date('Y-m-1 23:59:59').' -1 day')));
        $cond['ecm_order.pay_time'] = array('between',array($first_day,$last_day));
        $res = M('order')->join('left join ecm_member on ecm_order.buyer_id = ecm_member.user_id')
                        ->join('left join ecm_store on ecm_member.s_id = ecm_store.store_id')
                        ->field('ecm_member.*,sum(ecm_order.order_amount) as order_amount')
                        ->group('ecm_member.user_id')
                        ->where($cond)
                        ->select();
        foreach($res as $key => $value){
            $res_account = M('account')->where(array('user_id'=>$value['user_id']))->order('start_time desc')->find();
            if(!$res_account){
                $account_num = 1  ;
            }else{
                $account_num = $res_account['account_num'] + 1;
            }
            $data['account_num'] = $account_num;
            $data['user_id'] = $value['s_id'];
            $data['start_time'] = $first_day;
            $data['end_time'] = $last_day;
            $data['money'] = $value['order_amount'];
            $data['state'] = 0;
            $res = M('account')->add($data);
            if(!$res){
                return false;
            }

        }
    }


    /**
     *  定时设定每天更新今日上新产品
     *  User：lixinguo
     *  Time：2019/9/23
     */
    public function setTodayProduct()
    {
        $goodsModel = M("goods");
        $sortSettingModel = M("sortSetting");
        //获取今日开始时间戳和结束时间戳
        $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;

        $toDay = date('Y-m-d');

        $where['add_time'] = array('between',array($beginToday,$endToday));
        $where['if_show'] = 1;
        $where['closed'] = 0;
        //定时查询合适的商品
        $goodsSpec = new GoodsSpecModel();

        $goods_list = $goodsModel->where($where)->select();
        $result = $goodsSpec->troubleshootingStock($goods_list);
        //排除掉库存为0的数据
        $num = 1;
        $count = count($result);
        while($count < 100){
            $beginToday = mktime(0,0,0,date('m'),date('d')-$num,date('Y'));
            $endToday   = mktime(0,0,0,date('m'),date('d')+1-$num,date('Y'))-1;
            $filter['if_show'] = 1;
            $filter['closed'] = 0;
            $filter['add_time'] = array('between',array($beginToday,$endToday));
            $goods_list = $goodsModel->where($filter)->select();
            $result1 = $goodsSpec->troubleshootingStock($goods_list);
            $result = array_merge($result1,$result);
            $count += count($result1);
            $num ++;
        }
        $result = array_values($result);
        //查询今日上新的产品
        $sortSettingInfo = $sortSettingModel->where(array('sort_id'=>4))->find();
        $sortArr = explode(',',$sortSettingInfo);
        //把得到的goods_id拼接起来
        $ids = '';
        foreach($result as $k=>$v){
            //加上判断 防止定时循环时覆盖
            if(!in_array($v['goods_id'],$sortArr)){
                if($k==0){
                    $ids = $v['goods_id'];
                }else{
                    $ids .= ','.$v['goods_id'];
                }
            }
        }

        $saveData['goods_id'] = $ids;

        $sortSettingModel->startTrans();
        $save = $sortSettingModel->where(array('sort_id'=>4))->save($saveData);
        if(!$save){
            $sortSettingModel->rollback();
        }
        $sortSettingListModel = M("sortSettingList");

        $sortInfo = $sortSettingListModel->where(array('date'=>$toDay))->find();
        if(empty($sortInfo)){
            $saveData['date'] = $toDay;
            $saveList = $sortSettingListModel->add($saveData);
        }else{
            $saveList = $sortSettingListModel->where(array('date'=>$toDay))->save($saveData);
        }
        if(!$saveList){
            $sortSettingModel->rollback();
        }
        $sortSettingModel->commit();

    }

    public function test(){
        $send_array = array(
          'sku' => '123'
        );
        $res = sync_data(C('ERP_URL'),$send_array);
        var_dump($res);exit;
    }


    public function sendMessage(){
        $res_user = M('member')->count();
        $model = new \Home\Model\MsglogModel();
//        $model->send_msg('3','Admin','13820126986','截止到'.date("Y-m-d H:i").'共注册了'.$res_user.'个用户');
        $model->send_msg('165','Admin','13810206666','截止到'.date("Y-m-d H:i").'共注册了'.$res_user.'个用户');

    }

    public function refundWish(){
//        if(!I('request.wish_id')){
//            render('10400', '请选择心愿单');
//        }
        $cond['add_time'] = array('elt',time()-86400);
        $cond['state'] = 1;
        $res = M('wish')->where($cond)->select();
        foreach ($res as $k => $v){
            $time = date('YmdHis', time() + 8 * 3600) . rand(1000, 9999);
            $res_pay = M('wish_pay_log')->where(array('wish_id'=>$v['id']))->find();
            if($res_pay['pay_type'] == 1){
                include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Data.php";
                include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Api.php";
                include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epaywxnative/lib/WxPay1.Config.php";
                $input = new \WxPayRefund();
                $input->SetOut_trade_no($res_pay['order_sn']);
                $input->SetTotal_fee($res_pay['money'] * 100);
                $input->SetRefund_fee($res_pay['money'] * 100);
                $config = new \WxPay1Config();
                $input->SetOut_refund_no(date('YmdHis', time() + 8 * 3600) . rand(1000, 9999));
//            $input->SetOp_user_id($config->GetMerchantId());
                $rs = \WxPay1Api::refund($config,$input, 60);
//                $this->printf_info(WxPay1Api::refund($config,$input, 60));
                if($rs['return_code'] != 'SUCCESS'){
                    render('10004', '退款失败');
                }
                $data_oms = array(
                    'ClientGuid' => '4CC68510-AAD3-4DBC-9131-F00E5FFD2E75',
                    'ClientName' => 'ASA-ShoppingMall',
                    'BillNo' => date("YmdHis",$v['add_time']).$v['id'],
                    'BillType' => 20,
                    'PayName' => '财付通支付科技有限公司',
                    'PayCode' => '4403169D3W',
                    'PayTransactionId' => $rs['transaction_id'],
                    'PayPrice' => (float)($rs['refund_fee'] / 100),
                    'RefundNo' => $time
                );
            }else if($res_pay['pay_type'] == 2){
                include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/Alipay/aop/AopCertClient.php";
                include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/Alipay/aop/request/AlipayTradeRefundRequest.php";
                $appCertPath = "/data/wwwroot/default/ecmall/includes/alicert/appCertPublicKey_2019052465373222.crt";
                $alipayCertPath = "/data/wwwroot/default/ecmall/includes/alicert/alipayCertPublicKey_RSA2.crt";
                $rootCertPath = "/data/wwwroot/default/ecmall/includes/alicert/alipayRootCert.crt";
                $aop = new \AopCertClient();
                $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
                $aop->appId = C('app_alipay_partner_id');
                $aop->rsaPrivateKey =C('app_alipay_private_key');
                $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
                $aop->apiVersion = '1.0';
                $aop->signType = 'RSA2';
                $aop->postCharset='UTF-8';
                $aop->format='json';
                $aop->isCheckAlipayPublicCert = true;//是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
                $aop->appCertSN = $aop->getCertSN($appCertPath);//调用getCertSN获取证书序列号
                $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);//调用getRootCertSN获取支付宝根证书序列号
                $request = new \AlipayTradeRefundRequest ();

                //商户订单号，商户网站订单系统中唯一订单号
                $out_trade_no = trim($res_pay['order_sn']);
                //需要退款的金额，该金额不能大于订单金额，必填
                $refund_amount = trim($res_pay['money']);

                $request->setBizContent("{" .
                    "\"out_trade_no\":\"$out_trade_no\"," .
                    "\"trade_no\":\"\"," .
                    "\"refund_amount\":\"$refund_amount\"," .
                    "\"refund_reason\":\"正常退款\"" .
                    "  }");
                $result = $aop->execute($request);
//            $rs= json_decode(json_encode($result),true);
                $response = $result->alipay_trade_refund_response;
//                $config = include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/config.php";
//                include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/pagepay/service/AlipayTradeService.php";
//                include_once BASE_PATH."appserver/ThinkPHP/Library/Mall/Payment/epayalipay/epayalipayrefund/pagepay/buildermodel/AlipayTradeRefundContentBuilder.php";
//                //商户订单号，商户网站订单系统中唯一订单号
//                $out_trade_no = trim($res_pay['order_sn']);
//
//                //支付宝交易号
////                $trade_no = trim($_POST['WIDTRtrade_no']);
//                //请二选一设置
//
//                //需要退款的金额，该金额不能大于订单金额，必填
//                $refund_amount = trim($res_pay['money']);
//
//                //退款的原因说明
////                $refund_reason = trim($_POST['WIDTRrefund_reason']);
//
//                //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
////                $out_request_no = trim($_POST['WIDTRout_request_no']);
//
//                //构造参数
//                $RequestBuilder=new \AlipayTradeRefundContentBuilder();
//                $RequestBuilder->setOutTradeNo($out_trade_no);
////                $RequestBuilder->setTradeNo($trade_no);
//                $RequestBuilder->setRefundAmount($refund_amount);
////                $RequestBuilder->setOutRequestNo($out_request_no);
////                $RequestBuilder->setRefundReason($refund_reason);
//                $aop = new \AlipayTradeService($config,true);
//                $response = $aop->Refund($RequestBuilder);

                if($response->code != '10000'){
                    render('10004', '退款失败');
                }
                $data_oms = array(
                    'ClientGuid' => '4CC68510-AAD3-4DBC-9131-F00E5FFD2E75',
                    'ClientName' => 'ASA-ShoppingMall',
                    'BillNo' => date("YmdHis",$v['add_time']).$v['id'],
                    'BillType' => 20,
                    'PayName' => '财付通支付科技有限公司',
                    'PayCode' => '4403169D3W',
                    'PayTransactionId' => $response->trade_no,
                    'PayPrice' => $response->refund_fee,
                    'RefundNo' => $time.rand('1000,9999')
                );
            }else{
                render('10004', '未找到心愿单');
            }


            $res = sync_data(C('CANCEL_WISH_URL'),$data_oms);

            $data_wish = array(
                'state' => 3,
                'finish_time' => time()
            );
            $res_pay = M('wish')->where(array('id'=>$v['id']))->save($data_wish);
            if($res_pay === false){
                render('10004', '修改状态失败');
            }
            $res_spec = M('goods_spec')->where(array('spec_id'=>$v['spec_id']))->setInc('stock');

            if(!$res_spec){
                render('10004', '库存回滚失败');
            }
//            render('10000', '退款成功');
        }

    }

    //自动完成订单

    public function auto_finished_order(){
        $res = M('order')->where(array('status'=>30,'auto_finished_time' => array('elt',time())))->select();
        foreach ($res as $key => $value){
            M('order')->startTrans();
            $res_order_goods = M('order')->where(array('order_id'=>$value['order_id']))->find();
            if (!$res_order_goods){
                M('order')->rollback();
                return false;
            }
            $res_save = M('order')->where(array('order_id'=>$value['order_id']))->save(array('status'=>40,'finished_time'=>time()));
            if (!$res_save){
                M('order')->rollback();
                return false;
            }
            $data_log = array(
                'order_id' => $value['order_id'],
                'operator' => 'system',
                'order_status' => '已发货',
                'changed_status' => '已完成',
                'remark' => '确认收货超时,系统自动确认收货',
                'log_time' => time(),
                'operator_type' => 'buyer',
            );
            $res_log = M('order_log')->add($data_log);
            if (!$res_log){
                M('order')->rollback();
                return false;
            }

            //判断是否为推荐人
            //粉丝
            $res_member = M('member')->where(array('user_id'=>$value['buyer_id']))->find();
            if (!$res_member){
                M('order')->rollback();
                return false;
            }
            if($res_member['referid']){
                //推荐人
                $res_refer = M('member')->where(array('user_id'=>$res_member['referid']))->find();
                if (!$res_refer){
                    M('order')->rollback();
                    return false;
                }
                if($res_refer['is_promoters'] == 1 && $res_member['first_class'] == 2 && $res_member['second_class'] == $res_refer['id'] &&  $res_member['third_class'] == $res_refer['id']){
                    //修改入账detail完成订单时间
                    $res_commission_detail = M('commission_detail')->where(array('order_id'))->save(array('order_finish_time'=>time()));
                    if (!$res_commission_detail){
                        M('order')->rollback();
                        return false;
                    }

                }
            }

            $data_oms = array(
                'OrderNo' => $value['order_sn'],
                'OrderStatusId' => 1000
            );

            M('order')->commit();
            $url = C('FINISH_ORDER');
            _curl_to_oms($url,$data_oms);

        }
    }

    //自动结算佣金(废弃)

    public function auto_settlement_commission(){
        $res = M('order')->where(array('finished_time'=>array('elt',time() - 30 * 86400),'is_change' => 0,'status'=>40,'commission_amount'=>array('gt','0.00')))->select();
        foreach ($res as $key => $value){
            M('member')->startTrans();
            $res_member = M('member')->where(array('user_id'=>$value['buyer_id']))->find();
            //推荐人
            if(!$res_member){
                M('member')->rollback();
                return false;
            }
            $res_refer = M('member')->where(array('user_id'=>$res_member['referid']))->find();
            if(!$res_refer){
                M('member')->rollback();
                return false;
            }
            $res_member_save = M('member')->where(array('user_id'=>$res_refer['user_id']))->save(array('commission_dj'=>(float)$res_refer['commission_dj']+(float)$value['commission_amount']));
            if(!$res_member_save){
                M('member')->rollback();
                return false;
            }
            $res_order_save = M('order')->where(array('order_id'=>$value['order_id']))->save(array('is_change'=>1));
            if(!$res_order_save){
                M('member')->rollback();
                return false;
            }
            $data_commission = array(
                'user_id' => $res_refer['user_id'],
                'sign' => '+',
                'commission_money' => $value['commission_amount'],
                'finish_time' => time(),
                'remark' => '佣金结算'
            );
            $res_commission = M('commission')->add($data_commission);
            if (!$res_commission){
                M('order')->rollback();
                return false;
            }
            $data_commission_log = array(
                'user_id' => $res_refer['user_id'],
                'fans_id' => $res_member['user_id'],
                'sign' => '+',
                'order_id' => $value['order_id'],
                'order_money' => $value['order_amount'],
                'commission_money' => $value['commission_amount'],
                'finish_time' => time()
            );
            $res_commission_log = M('commission_log')->add($data_commission_log);
            if (!$res_commission_log){
                M('order')->rollback();
                return false;
            }
            M('member')->commit();

        }
    }

    //自动生成订单

    public function auto_create_account(){
        //取上上个月21到上个月20
        //上个月时间(time)
        $last_month_time= strtotime(date("Y-m-d H:i:s", strtotime("-1 month")));
        //上上个月时间(time)
        $last_last_month_time = strtotime(date("Y-m-d H:i:s", strtotime("-2 month")));
        //上上个月21号
        $start_time = strtotime(date('Y',$last_last_month_time).'-'.date('m',$last_last_month_time).'-21');
        //上个月20号
        $end_time = strtotime(date('Y',$last_month_time).'-'.date('m',$last_month_time).'-20 23:59:59');
        var_dump(date("Y-m-d",$start_time));
        var_dump(date("Y-m-d",$end_time));exit;
        $res = M('commission_detail')->field('user_id,SUM(CONVERT (REPLACE(CONCAT(sign,commission),"+","") , DECIMAL(9,2))) as commision_amount,SUM(CONVERT (REPLACE(CONCAT(sign,price_amount),"+","") , DECIMAL(9,2))) as order_amount')->where(array('order_finish_time'=>array('between',array($start_time,$end_time))))->group('user_id')->select();
        foreach ($res as $key => $value){
            M('commission_detail')->startTrans();
            $data_commission_account = array(
                'user_id' => $value['user_id'],
                'account_no' => date('YmdHis', time() + 8 * 3600) . rand(1000, 9999),
                'comminssion_money' => $value['commision_amount'],
                'order_money' => $value['order_amount'],
                'start_time' => $start_time,
                'end_time' => $end_time

            );
            $res_commission_account = M('member')->add($data_commission_account);
            if(!$res_commission_account){
                M('commission_detail')->rollback();
                return false;
            }
            $cond_commission_detail = array(
                'order_finish_time' => array('between',array($start_time,$end_time)),
                'user_id' => $value['user_id'],
            );
            $res_commission_detail = M('commission_detail')->where($cond_commission_detail)->save(array('account_id'=>$res_commission_account));
            if(!$res_commission_detail){
                M('commission_detail')->rollback();
                return false;
            }
            M('member')->commit();

        }
    }

    //自动结算佣金入虚拟账户

    public function auto_add_commission(){
        $res_commission_log = M('commission_log')->where(array('status'=>1))->select();
        foreach ($res_commission_log as $k => $v){
            M('commission_log')->startTrans();
            $res_commission_log_save = M('commission_log')->where(array('status'=>1))->save(array('status'=>2));
            if(!$res_commission_log_save){
                M('commission_log')->rollback();
                return false;
            }
            $res_member = M('member')->where(array('user_id'=>$v['user_id']))->find();
            $res_member_save = M('member')->where(array('user_id'=>$v['user_id']))->save(array('commission'=>(float)$res_member['commission'] + (float)$v['commission_money ']));
            if(!$res_member_save){
                M('commission_log')->rollback();
                return false;
            }
            M('member')->commit();
        }
    }






}

//下载远程图片

function downloadImage($url,$path,$type,$res)
{
    // 暂时注释
    // if(get_between($url,':','/')){
    //     $port = '80';
    // }else{
    //     $port = get_between($url,':','/');
    // }

    // port获取方式改变，Powered by liuzongyang 2019/12/17 17:18
    $r = parse_url($url);
    $port = $r['port'];


    $ch = curl_init(); //curl_init(): 初始化一个新的会话，返回一个cURL句柄，供curl_setopt(), curl_exec()和curl_close() 函数使用。

    curl_setopt($ch, CURLOPT_URL, $url);//curl_setopt(): 设置一个cURL传输选项,

//CURLOPT_URL: 需要获取的 URL 地址，也可以在curl_init() 初始化会话的时候。

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //CURLOPT_RETURNTRANSFER: TRUE将curl_exec()获取的信息以字符串返回，而不是直接输出。

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);//CURLOPT_CONNECTTIMEOUT: 在尝试连接时等待的秒数。设置为0，则无限等待。

    curl_setopt($ch, CURLOPT_PORT, $port);

    $file = curl_exec($ch);//curl_exec(): 执行一个cURL会话

    if($file === false){
        $send_array[] = array(
            'Sku' => $res['swift_number'],
            'Field' => '',
            'Msg' => '远程下载图片失败',
            "Result" => 0
        );
        sync_data(C('ERP_URL'),$send_array);
        return false;
    }

    curl_close($ch);//curl_close(): 关闭一个cURL会话

    $rs = mkdirs_1($path);
    if($rs === false){
        $send_array[] = array(
            'Sku' => $res['swift_number'],
            'Field' => '',
            'Msg' => '创建文件夹失败',
            "Result" => 0
        );
        sync_data(C('ERP_URL'),$send_array);
        return false;
    }

    $result = saveAsImage($url, $file, $path, $type,$res);
    return $result;
}

//字符串截图某一位
function get_between($input, $start, $end) {
    $substr = substr($input, strlen($start)+strpos($input, $start),(strlen($input) - strpos($input, $end))*(-1));
    return $substr;
}

//type
// 1:商品主图

// 2:商品规格图

function saveAsImage($url, $file, $path ,$type = 1,$res)
{
    $filenames = pathinfo($url, PATHINFO_BASENAME);//pathinfo(): 返回文件路径的信息
    $str=explode('.',$filenames);
    if($type == 2){
        $filename = 'spec_'.date("YmdHis").(time() % 200).rand(100000,999999).'.'.$str[1];
        $resource = fopen($path.$filename, 'a');//fopen(): 打开文件或url
    }else{
        $filename = date("YmdHis".(time()) % 200).rand(100000,999999).'.'.$str[1];
        $resource = fopen($path.$filename, 'a');//fopen(): 打开文件或url
    }
    $rs = fwrite($resource, $file);//fwrite(): 写入文件
    fclose($resource);//fclose(): 关闭一个已经打开的文件指针
    return $filename;
}

function mkdirs_1($path, $mode = 0777){
    if(is_dir($path)){
        return '无法创建,已经是目录了';
    }else{
        if(mkdir($path, $mode, true)) {
            return '创建成功';
        }else{
            return '创建失败';
        }
    }
}

//制作缩略图
function make_thumb($thumb_path,$save_path){
    $image = new \Think\Image();
    $image->open($thumb_path);
    $image->thumb(300, 300,\Think\Image::IMAGE_THUMB_FIXED)->save($save_path);
}

//存数据库(4张表)
function save_sql($data,$type,$res_goods){
    $file_model = M('uploaded_file');
    $goods_image_model = M('goods_image');
    $goods_model = M('goods');
    $goods_spec_model = M('goods_spec');
    $data_file = array();
    if($type == 1 || $type == 3){
        $data_file = array(
            'store_id'=>$data['store_id'],
            'file_type'=>'image/jpeg',
            'file_name'=>$data['file_name'],
            'file_path'=>$data['file_path'],
            'add_time'=> time(),
            'belong'=>2,
            'item_id'=>$data['goods_id']
        );
    }else{
        $data_file = array(
            'store_id'=>$data['store_id'],
            'file_type'=>'image/jpeg',
            'file_name'=>$data['file_name'],
            'file_path'=>$data['file_path'],
            'add_time'=> time(),
            'belong'=>6,
            'item_id'=>$data['goods_id']
        );
    }
    $res = $file_model->add($data_file);
    if(!$res){
        $send_array[] = array(
            'Sku' => $res_goods['swift_number'],
            'Field' => '',
            'Msg' => '添加图片(file)失败',
            "Result" => 0
        );
        sync_data(C('ERP_URL'),$send_array);
        return false;
    }
    if($type == 1){
        $data_image = array(
            'goods_id'=>$data['goods_id'],
            'image_url'=>$data['file_path'],
            'thumbnail'=>$data['thumb_path'],
            'file_id'=>$res
        );
        $res = $goods_image_model->add($data_image);
        if(!$res){
            $send_array[] = array(
                'Sku' => $res_goods['swift_number'],
                'Field' => '',
                'Msg' => '添加图片(goods_image)失败',
                "Result" => 0
            );
            sync_data(C('ERP_URL'),$send_array);
            return false;
        }

    }
    if($type == 1){
        $data_goods = array(
            'default_image'=>$data['file_path'],
        );
        $res = $goods_model->where(array('goods_id'=>$data['goods_id']))->save($data_goods);
        if(!$res){
            $send_array[] = array(
                'Sku' => $res_goods['swift_number'],
                'Field' => '',
                'Msg' => '编辑商品(goods)失败',
                "Result" => 0
            );
            sync_data(C('ERP_URL'),$send_array);
            return false;
        }
    }

    if($type == 2){
        $data_goods_spec = array(
            'spec_1'=>$data['file_path'],
        );
        $res = $goods_spec_model->where(array('spec_id'=>$data['spec_id']))->save($data_goods_spec);
        if(!$res){
            $send_array[] = array(
                'Sku' => $res_goods['swift_number'],
                'Field' => '',
                'Msg' => '编辑规格(spec)失败',
                "Result" => 0
            );
            sync_data(C('ERP_URL'),$send_array);
            return false;
        }
    }

    if($type == 3){
        $res_description = M('goods')->where(array('goods_id'=>$data['goods_id']))->find();
        if(!$res_description){
            $send_array[] = array(
                'Sku' => $res_goods['swift_number'],
                'Field' => '',
                'Msg' => '编辑规格(spec)失败',
                "Result" => 0
            );
            sync_data(C('ERP_URL'),$send_array);
            return false;
        }
        if(!strstr($res_description['description'],'<p>')){
            $str = '<p><img src="./'.$data['file_path'].'"/></p>';
            $data_goods = array(
                'description'=>$str,
            );
        }else{
            //临时加第一张图
//            $temp_str = str_replace('<p>','',$res_description['description']);
//            $str = '<p><img src="./'.$data['file_path'].'"/>'.$temp_str;
//            $data_goods = array(
//                'description'=>$str,
//            );

            $temp_str = str_replace('</p>','',$res_description['description']);
            $str = $temp_str.'<img src="./'.$data['file_path'].'"/></p>';
            $data_goods = array(
                'description'=>$str,
            );
        }
        $res = $goods_model->where(array('goods_id'=>$data['goods_id']))->save($data_goods);
        if(!$res){
            $send_array[] = array(
                'Sku' => $res_goods['swift_number'],
                'Field' => '',
                'Msg' => '编辑富文本(goods)失败',
                "Result" => 0
            );
            sync_data(C('ERP_URL'),$send_array);
            return false;
        }
    }
    $res_save = M('save_images')->where(array('id'=>$data['id']))->save(array('is_save'=>1));
    if(!$res_save){
        $send_array[] = array(
            'Sku' => $res_goods['swift_number'],
            'Field' => '',
            'Msg' => '标记is_excute=1失败',
            "Result" => 0
        );
        sync_data(C('ERP_URL'),$send_array);
        return false;
    }

    Log::write(print_r($data_goods,true,'','','',C('LOG_PATH').date('y_m_d').'(Crontab/Index/saveimages).log'));
    return true;
}

function sync_data($url, $data_string) {
    $data_string = json_encode($data_string);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    //https
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // https请求 不验证证书和hosts
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    //
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data_string))
    );
    ob_start();
    $res = curl_exec($ch);
    if(!$res){
        return false;
    }else{
        return true;
//        return json_decode($res,true);
    }
//    $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//    $return_content = ob_get_contents();
//    ob_end_clean();
//
    return array('code'=>$return_code, 'result'=>$return_content);
}
